#include "Utils.hpp"

namespace ss 
{
	namespace utls 
	{
		bool Split(CoChar_t sep, CoCStr_t raw, VSplit_t& split_values)
		{
			Str_t line(raw);
			size_t pos = 0;
			while((pos = line.find_first_of(sep)) != std::string::npos)
			{
				split_values.push_back(line.substr(0, pos));
				line = line.substr(pos+1, line.size());
			}
			split_values.push_back(line);
			if (split_values.size() == 0) return false;

			return true;
		}

		Str_t CurrentDir(void)
		{
			char rawDir[FILENAME_MAX];
			GetCurrentDir(rawDir, FILENAME_MAX);			
			return std::string(rawDir);
		}

		size_t NumOfDirLevels(void)
		{			
			VSplit_t dirs;			
			Split(GetDirSep(), CurrentDir().c_str(), dirs);
			return dirs.size();
		}

		Str_t DirLevel(CoUInt_t Level)
		{
			VSplit_t dirs;
			Str_t Dir;
			Split(GetDirSep(), CurrentDir().c_str(), dirs);
			if (Level > 0 && Level < dirs.size())			
			{
				Dir.clear();
				size_t i = 0;
				for(VSplit_t::iterator it = dirs.begin(); i < Level && it != dirs.end(); it++, i++)				
				{
					if (it == dirs.begin())
						Dir.append(*it);				
					else
						Dir.append(GetDirSep() + *it);				
				}
			}
			return Dir;
		}
	
		Char_t GetDirSep(void)
		{			
			Str_t like_unix = CurrentDir().substr(0, 1);
			Str_t like_win  = CurrentDir().substr(1, 2);

			if ( like_unix.compare("/") == 0 )
				return '/';
			else if ( like_win.compare(":\\") == 0 ) 
				return '\\';
			
			return '#';

		}

		Str_t GetDirSepToStr(void)
		{
			Buffer_t ss;
			ss << GetDirSep();			
			return ss.str();
		}

		Str_t FixWinPath(CoStr_t& path)
		{
			size_t len = path.size();
			if (len == 0) return "";
			Str_t n_path;
			n_path.resize(len+1);
			char* c_str = new char[len+1];		
			memset(c_str, 0, len+1);
			strncpy(c_str, path.c_str(), len);
			size_t x = 0;
			for(size_t i = 0; i < len; i++)
			{
				if (*(c_str+i) == '\\' && *(c_str+i+1) != '\\')
				{
					n_path.resize(n_path.size()+1);
					n_path[x++] = '\\';
				}
				n_path[x++] = *(c_str+i);
			}
			delete[] c_str;
			c_str = NULL;

			return n_path;
		}

		Str_t ExtractEXTENSION(CoStr_t& path)
		{
			return path.substr(path.find_last_of(".")+1, path.size());
		}

		bool GetFile(CoStr_t& path, Str_t& stream)
		{
			std::ifstream is(path.c_str());
			if (is.is_open())
			{
				is.seekg(0, std::ios::beg);
				std::stringstream ss;
				ss << is.rdbuf();
				is.close();
				stream = ss.str();
				is.close();
			} else return false;
			return true;
		}
			
	}
}